<template>
  <div class="container">

    <el-container>
      <!--  左布局，个人信息-->
      <el-aside>
        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <span>个人信息</span>
          </div>
          <!--          头像上传-->
          <div style="text-align: center;border-radius: 50%">
            <!-- 
            action="http://localhost:8081/upload"	后端接口地址，文件会通过 POST 请求发送到该 URL。
            :show-file-list="false"	隐藏文件列表（适合单文件上传场景）。
            :on-success="handleAvatarSuccess"	上传成功后的回调函数，接收服务器响应。
            :before-upload="beforeAvatarUpload"	上传前的校验函数，可限制文件类型/大小。
            -->
            <el-upload
                class="avatar-uploader"
                action="http://localhost:8081/api/upload"
                :show-file-list="false"
                :on-success="handleAvatarSuccess"
                :on-error="handleUploadError"
                :before-upload="beforeAvatarUpload">
              <img v-if="imageUrl" :src="imageUrl" title="1" alt="加载失败" class="avatar"
                   style="border-radius: 50%;width: 120px;height: 120px">
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </div>

          <!--信息展示-->
          <template>
            <div class="form1">
              <el-divider></el-divider>
              <el-row>
                <el-col :span="12">
                  <div class="grid-content bg-purple"><span><i class="el-icon-user-solid">&nbsp;</i>用户名称 </span></div>
                </el-col>
                <el-col :span="12">
                  <div class="grid-content bg-purple-light" style="text-align: right"><span>{{ user.userName }}</span>
                  </div>
                </el-col>
              </el-row>
              <el-divider></el-divider>
              <el-row>
                <el-col :span="12">
                  <div class="grid-content bg-purple"><span><i class="el-icon-phone-outline">&nbsp;</i>手机号码 </span>
                  </div>
                </el-col>
                <el-col :span="12">
                  <div class="grid-content bg-purple-light" style="text-align: right">
                    <span>{{ user.phonenumber }}</span></div>
                </el-col>
              </el-row>
              <el-divider></el-divider>
              <el-row>
                <el-col :span="12">
                  <div class="grid-content bg-purple"><span><i class="el-icon-s-home ">&nbsp;</i>用户邮箱 </span></div>
                </el-col>
                <el-col :span="12">
                  <div class="grid-content bg-purple-light" style="text-align: right"><span>{{ user.email }}</span>
                  </div>
                </el-col>
              </el-row>
              <el-divider></el-divider>
              <el-row>
                <el-col :span="12">
                  <div class="grid-content bg-purple"><span><i class="el-icon-school">&nbsp;</i>所属部门 </span></div>
                </el-col>
                <el-col :span="12">
                  <div class="grid-content bg-purple-light" style="text-align: right">
                    <span>{{ user.deptName }}</span>
                  </div>
                </el-col>
              </el-row>
              <el-divider></el-divider>
              <el-row>
                <el-col :span="12">
                  <div class="grid-content bg-purple"><span><i class="el-icon-s-check">&nbsp;</i>所属角色 </span></div>
                </el-col>
                <el-col :span="12">
                  <div class="grid-content bg-purple-light" style="text-align: right"><span>{{ user.remark }}</span>
                  </div>
                </el-col>
              </el-row>
              <el-divider></el-divider>
              <el-row>
                <el-col :span="12">
                  <div class="grid-content bg-purple"><span><i class="el-icon-date">&nbsp;</i>创建日期 </span></div>
                </el-col>
                <el-col :span="12">
                  <div class="grid-content bg-purple-light" style="text-align: right"><span>{{ user.createTime }}</span>
                  </div>
                </el-col>
              </el-row>
              <el-divider></el-divider>
            </div>
          </template>

        </el-card>
      </el-aside>

      <!--右布局-->
      <el-main style="padding: 0px 0px 0px 20px">
        <el-card class="box-card" style="height: 513px">
          <div slot="header" class="clearfix">
            <span>基本资料</span>
          </div>
          <!--  标签页-->
          <template>
            <el-tabs v-model="activeName">
              <el-tab-pane label="基本资料" name="first">
                <!--基本资料-->
                <el-form :model="form" :rules="rules" ref="forms" label-width="80px">
                  <el-form-item label="用户昵称" prop="nickName">
                    <el-input v-model="form.nickName"></el-input>
                  </el-form-item>
                  <el-form-item label="手机号码" prop="phonenumber">
                    <el-input v-model="form.phonenumber"></el-input>
                  </el-form-item>
                  <el-form-item label="邮箱" prop="email">
                    <el-input v-model="form.email"></el-input>
                  </el-form-item>
                  <el-form-item label="性别">
                    <el-radio-group v-model="form.sex">
                      <el-radio v-model="radio" label="0">男</el-radio>
                      <el-radio v-model="radio" label="1">女</el-radio>
                    </el-radio-group>
                  </el-form-item>
                  <el-form-item>
                    <el-popover
                        placement="top"
                        width="160"
                        v-model="visible">
                      <p>你确认要修改吗？</p>
                      <div style="text-align: right; margin: 0">
                        <el-button size="mini" type="text" @click="visible = false">取消</el-button>
                        <el-button type="primary" size="mini" @click="onSubmit('forms')">确定</el-button>
                      </div>
                      <el-button type="primary" size="mini" slot="reference">保存</el-button>
                    </el-popover>
                    <el-button size="mini" @click="closeUserInfo">关闭</el-button>
                  </el-form-item>
                </el-form>
              </el-tab-pane>


              <!-- 修改密码-->
              <el-tab-pane label="修改密码" name="second">
                <template>
                  <el-form :model="ruleForm" :rules="rule" ref="ruleForms" label-width="80px">
                    <el-form-item label="旧密码" prop="oldPassword">
                      <el-input v-model="ruleForm.oldPassword" placeholder="请输入旧密码" type="password"/>
                    </el-form-item>
                    <el-form-item label="新密码" prop="newPassword">
                      <el-input v-model="ruleForm.newPassword" placeholder="请输入新密码" type="password"/>
                    </el-form-item>
                    <el-form-item label="确认密码" prop="confirmPassword">
                      <el-input v-model="ruleForm.confirmPassword" placeholder="请确认密码" type="password"/>
                    </el-form-item>
                    <el-form-item>
                      <el-button type="primary" size="mini" @click="openVerificationDialog">保存</el-button>
                      <el-button type="danger" size="mini" @click="resetForms('ruleForms')">重置</el-button>
                    </el-form-item>
                  </el-form>
                </template>
              </el-tab-pane>

            </el-tabs>
          </template>

        </el-card>


      </el-main>
    </el-container>
    <!-- 弹出框 -->
    <el-dialog
        title="验证手机号"
        :visible.sync="dialogVisible"
        width="400px"
        :close-on-click-modal="false"
        :before-close="handleClose"
    >
      <el-form :model="verificationForm" :rules="rules2" ref="verificationForm" label-width="80px"
               label-position="right" class="verification-form">
        <el-form-item label="手机号" prop="phone" class="inline-item">
          <el-input
              v-model="verificationForm.phone"
            placeholder="请输入手机号码"
            clearable
            style="width: 200px"
          ></el-input>
        </el-form-item>
        
        <el-form-item label="验证码" prop="code" class="code-item">
          <div class="code-wrapper">
            <el-input
              v-model="verificationForm.code"
              placeholder="请输入验证码"
               style="width: 140px"
              clearable
            ></el-input>
            <el-button
              type="primary"
              size="small"
              :disabled="countdown > 0 || !isPhoneValid"
              @click="getVerificationCode"
              style="margin-left: 10px; width: 100px"
            >
              {{ countdown > 0 ? `${countdown}秒后重试` : '获取验证码' }}
            </el-button>
          </div>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitVerification">确 定</el-button>
      </span>
    </el-dialog>
  </div>

</template>

<script>
export default {
  // 全局刷新
  inject: ['reload'],
  data() {
    return {
      fits: ['cover'],
      url: '',
      radio: "男",
      activeName: 'first',
      imageUrl: '',
      form: {
        userId: "默认值",
        nickName: "XXX",
        userName: "XXX",
        phonenumber: "19999999999",
        email: "12345456789@qq.com",
        sex: "0",
        password: "qwe123"
      },

      ruleForm: {
        oldPassword: "",
        newPassword: "",
        confirmPassword: ""
      },
      rule: {
        oldPassword: [
          {required: true, message: "旧密码不能为空", trigger: "blur"},
          {min: 6, max: 20, message: "长度在6到28个字符", trigger: ['blur', 'change']}
        ],
        newPassword: [
          {required: true, message: "新密码不能为空", trigger: "blur"},
          {min: 6, max: 20, message: "长度在6到28个字符", trigger: ['blur', 'change']}
        ],
        confirmPassword: [
          {required: true, message: "确认密码不能为空", trigger: "blur"},
          {required: true, validator: this.equalToPassword, trigger: ['blur', 'change']}
        ]
      },
      //表单校验
      rules: {
        nickName: [
          {required: true, message: "用户昵称不能为空", trigger: "blur"},
          {min: 1, max: 15, message: "长度在3到15个字符", trigger: "blur"}
        ],
        phonenumber: [
          {required: true, message: "手机号码不能为空", trigger: "blur"},
          {
            pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
            message: "请输入正确的手机号",
            trigger: ['blur', 'change']
          }
        ],
        email: [
          {required: true, message: "邮箱地址不能为空", trigger: "blur"},
          {
            type: "email",
            message: "请输入正确的邮箱地址",
            trigger: ["blur", "change"]
          }
        ]
      },
      user: {},
      visible: false,//修改基本信息保存弹出框
      //手机号
      dialogVisible: false,//修改密码保存弹出框
      countdown: 0,//60倒计时
      timer: null,
      verificationForm: {
        phone: '',
        code: ''
      },
      rules2: {
        phone: [
          {required: true, message: '请输入手机号码', trigger: 'blur'},
          {
            pattern: /^1[3-9]\d{9}$/,
            message: '请输入正确的手机号码',
            trigger: ['blur', 'change']
          },
          {validator: this.chenkPhone, trigger: ['blur', 'change']}
        ],
        code: [
          {required: true, message: '请输入验证码', trigger: 'blur'},
          {
            pattern: /^\d{4}$/,
            message: '验证码必须为4位数字',
            trigger: ['blur', 'change']
          }
        ]
      }
    }
  },
  created() {
    this.getSysUserAndDept();
  },
  methods: {
    /**
     * 验证两次新密码是否一致
     * @param rule 当前验证规则的配置
     * @param value 表示"确认密码"输入框的值
     * @param callback 回调函数，用于返回校验结果
     */
    equalToPassword(rule, value, callback) {
      if (this.ruleForm.newPassword !== value) {
        console.log("user-UserInfo->新密码为=", this.ruleForm.newPassword)
        console.log("user-UserInfo->确认密码为=", value)
        callback(new Error("两次输入的密码不一致"));
      } else {
        callback();
      }
    },
    //个人信息修改
    onSubmit(forms) {
      this.visible = false
      this.$refs[forms].validate((valid) => {
        if (valid) {
          this.$http.put("sys/updateUserInfo", this.form)
              .then((res) => {
                this.$message.success(res.data)
              })
              .catch((res) => {
                this.$message.error(res.msg)
              })
        } else {
          this.$message.error(' 修改失败！')
        }
      })
    },

    //个人信息修改面板  关闭按钮-》退出个人信息修改
    closeUserInfo() {
      this.$router.push('/welcome');
    },

    //修改密码   重置
    resetForms(ruleForms) {
      this.$refs[ruleForms].resetFields();
    },

    //图片展示成功
    //上传图片
    handleAvatarSuccess(response, file) {
      if (response && response.code === 200) {
        this.$message.success("上传成功")
        this.imageUrl = response.data
        window.sessionStorage.setItem("avatar", response.data);
        this.$http.get('/updateImg', {
          params: {
            userId: this.user.userId,
            avatar: response.data,
          }
        })
            .then((res) => {
              this.$message.success("更新成功")
              //让头部右侧图片也刷新
              this.reload();
            })
            .catch((res) => {
              this.$message.err(res.msg)
            })
      } else {
        this.$message.error(response.msg || '上传失败');
      }
      this.reload();
    },
    handleUploadError(err, file, fileList) {
      this.$message.error("上传错误");
    },
    /**
     * 图片上传需求
     * @param file
     * @returns {boolean}
     */
    beforeAvatarUpload(file) {
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!');
      }
      return isLt2M;
    },

    /**
     * 获取所有信息
     * @returns {Promise<void>}
     */
    getSysUserAndDept() {
      const userId = window.sessionStorage.getItem("userId")
      this.$http.get('sys/queryById', {params: {"userId": userId}})
          .then((res) => {
            console.log("user-userinfo->信息:", res.data.avatar)
            this.user = res.data;
            this.imageUrl = res.data.avatar
            this.form = {
              ...this.form,      // 保留 form 原有的字段（如 password 等）
              ...res.data
            }
          })
          .catch((res) => {
            this.$message.error(res.data.msg)
          })
    },
    //手机验证码相关
    //打开弹出框
    openVerificationDialog() {
      this.$refs.ruleForms.validate((valid) => {
        if (valid) {
          this.verificationForm.phone = this?.user?.phonenumber || ''
          this.dialogVisible = true
        } else {
          this.$message.warning("密码输入有误")
        }
      })


    },
    //获取验证码
    getVerificationCode() {
      if (!this.isPhoneValid) {
        this.$message.error('请输入正确的手机号码')
        return
      }

      // 这里调用发送验证码的API
      this.$http.get('sys/getCode', {params: {"phone": this.verificationForm.phone}})
          .then((res) => {
            this.$message.success(res.msg || "发送成功")
          }).catch(error => {
        this.$message.error(error.msg || '12发送验证码失败')
      })
      this.startCountdown()
    },
    //设置获取验证码倒计时
    startCountdown() {
      this.countdown = 60
      this.timer = setInterval(() => {
        this.countdown--
        if (this.countdown <= 0) {
          clearInterval(this.timer)
        }
      }, 1000)
    },
    //确认提交
    submitVerification() {
      this.$refs.verificationForm.validate((valid) => {
        if (valid) {
          // 这里调用验证接口
          this.$http.put("sys/updataPassword",
              {
                phone: this.verificationForm.phone,
                code: this.verificationForm.code,
                oldPassword: this.ruleForm.oldPassword,
                newPassword: this.ruleForm.newPassword,
                confirmPassword: this.ruleForm.confirmPassword
              }
          )
              .then((res) => {
                this.$message.success(res.data)
                this.dialogVisible = false
                this.resetForm()
                window.sessionStorage.clear();
                this.$router.push('/login')
              }).catch((res) => {
            this.$message.error(res.msg || '验证失败')
          })
        } else {
          this.$message.warning('提交正确的手机号与验证码')
        }
      })
    },
    //取消弹出框时候，关闭倒计时
    handleClose(done) {
      this.resetForm()
      done()
    },

    resetForm() {
      this.$refs.verificationForm.resetFields()
      clearInterval(this.timer)
      this.countdown = 0
    },
    //检查前后手机号是否一致
    chenkPhone(rule2, value, callback) {
      if (this.verificationForm.phone !== this.user.phonenumber) {
        this.$message.warning('与保存的手机号冲突，确定后会更改')
        // callback({ type: 'warning', message: '与保存的手机号冲突，确定后会更改' })
        callback();
      } else {
        callback();
      }
    }
  },
  //计算属性 计算是否打开获取验证码开关
  computed: {
    isPhoneValid() {
      return /^1[3-9]\d{9}$/.test(this.verificationForm.phone)
    }
  },
  beforeDestroy() {
    clearInterval(this.timer)
  }
}
</script>

<style scoped>
.el-divider--horizontal {
  margin: 13px 0;
}

.form1 {
  font-size: 13px;
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}

/* 表单整体样式 */
.verification-form {
  padding: 20px 30px;
}

/* 单行显示的表单项 */
.inline-item {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}

.inline-item >>> .el-form-item__content {
  margin-left: 0 !important;
}

/* 验证码区域 */
.code-item {
  margin-bottom: 0;
}

.code-wrapper {
  display: flex;
  align-items: center;
}

/* 调整对话框按钮位置 */
.dialog-footer {
  text-align: center;
  padding: 10px 20px 20px;
}
</style>


